package com.wy2cloud.core.security;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 安全密钥工具类
 * @author admin
 *
 */
public final class SecurityKeyUtils {

	public static KeyPair generatorKeyPair(String keyAlgorithm,int keySize) throws Exception {
        KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
        kpGenerator.initialize(keySize);
        KeyPair keyPair = kpGenerator.generateKeyPair();
        return keyPair;
    }
	
	public static KeyPair generatorKeyPair(EncryptType encryptType) throws Exception {
		return generatorKeyPair(encryptType.getAlgorithm(), encryptType.getSize());
	}
	
	/** 
     * 加载公钥 
     *  
     * @param publicKeyBytes
     *            公钥数据
     * @throws Exception 
     *             加载公钥时产生的异常 
     */  
    public static PublicKey loadPublicKey(byte[] publicKeyBytes)  
            throws Exception {  
        try {  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);  
            return keyFactory.generatePublic(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("公钥非法");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥数据为空");  
        }  
    }
    public static PrivateKey loadPrivateKey(byte[] privateKeyBytes)  
            throws Exception {  
        try {  
        	KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);  
            return keyFactory.generatePrivate(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("私钥非法");  
        } catch (NullPointerException e) {  
            throw new Exception("私钥数据为空");  
        }  
    }

    public static void main(String[] args) throws Exception {
        KeyPair keyPair = generatorKeyPair(EncryptType.RSA_1024);
        System.out.println("public:"+Base64Tools.encode(keyPair.getPublic().getEncoded()));
        System.out.println("private:"+Base64Tools.encode(keyPair.getPrivate().getEncoded()));
    }
}
